package com.sr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.sr.entity.Book;
import com.sr.entity.User;
import com.sr.util.BaseDao;


public class UserDao {
	/*
	 * 1.注册账号方法
	 */
	public boolean addUser(User u){
		try{
			Connection con=BaseDao.getConnection();
			PreparedStatement pstm=con.prepareStatement("insert into user(username,password) values(?,?)");
			pstm.setString(1, u.getUsername());
			pstm.setString(2, u.getPassword());
			int rs = pstm.executeUpdate();//自定义rs
			if(rs>0){
				return true;
			}else{
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	/*
	 * 根据name查询相应用户名  写完这个 下面还要写一个验证
	 */
public User findUserByUserName(String username) {
		try{
			Connection con=BaseDao.getConnection();
			PreparedStatement pstm=con.prepareStatement("select * from user where username=?");
			pstm.setString(1, username);
			ResultSet rs=pstm.executeQuery();
			User u=null;
			while(rs.next()){
				u=new User();
				u.setId(rs.getInt(1));
				u.setUsername(rs.getString(2));
				u.setPassword(rs.getString(3));
			}
			return u;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
/*
* 登录 验证该用户是否存在<根据username>
*/
	public boolean isExist(String username) {
		return findUserByUserName(username)==null?false:true;
}
	
	//2.再进行登录
	public boolean login(String username,String password){
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			 conn=BaseDao.getConnection();
			 ps=conn.prepareStatement("select * from user where username=? , password=?");
			 ps.setString(1, username);
			 ps.setString(2, password);
			 ResultSet rs=ps.executeQuery();
			 User user=null;
			// 展开结果集数据库
			 while(rs.next()){
				 user=new User();
				// 通过字段检索
				 user.setId(rs.getInt("id"));
				 user.setUsername(rs.getString("username"));
				 user.setPassword(rs.getString("password"));
				 System.out.println(user);
				 if(rs!=null){
					 return true;
				 }else{
					 return false;
				 }
			 }
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return false;
		
	}

	/*
	 * 注册 验证该用户名是否存在<根据id>
	 */
public boolean isExist(int id) {
	return findUserById(id)==null?false:true;
}

public User findUserById(int id) {
	return null;
}

}
